package ae.pcfc.cldos.online.web.controller.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ae.pcfc.cldos.online.common.clddb.dao.AppMetaDataDAO;
import ae.pcfc.cldos.online.common.clddb.dao.MessageInboxDAO;
import ae.pcfc.cldos.online.common.clddb.domain.MessageInbox;
import ae.pcfc.cldos.online.common.clddb.domain.TaskMaster;
import ae.pcfc.cldos.online.common.clddb.domain.manager.SequencesDOM;
import ae.pcfc.cldos.online.common.delegate.CityDelegate;
import ae.pcfc.cldos.online.common.delegate.EmirateCityDelegate;
import ae.pcfc.cldos.online.common.delegate.EmirateDelegate;
import ae.pcfc.cldos.online.common.delegate.EmploymentVisaDelegate;
import ae.pcfc.cldos.online.common.delegate.FileHandlerDelegate;
import ae.pcfc.cldos.online.common.delegate.SystemValuesDelegate;
import ae.pcfc.cldos.online.common.manager.BuisnessValidationManager;
import ae.pcfc.cldos.online.common.manager.FtlProcessorManager;
import ae.pcfc.cldos.online.common.messaging.GenericMessageProducer;
import ae.pcfc.cldos.online.common.vo.CommentsVO;
import ae.pcfc.cldos.online.common.vo.EmployeVisaVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.UserVO;
import ae.pcfc.cldos.online.common.vo.employee.details.AddressDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.EmployeeDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PassportDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PersonalDetailsVO;
import ae.pcfc.cldos.online.web.controller.base.BasePageController;
import ae.pcfc.cldos.online.web.model.EmploymentVisaLicenseInfo;
import freemarker.template.TemplateException;

/**
 * controller for tests
 * 
 * @author arosa
 *
 */
@Controller
@RequestMapping("/home")
public class TestHomeController extends BasePageController {

	
	public static final String ATATA = "asgasg";
	
//	@Autowired
//	@Qualifier("countryDelegate")
//	private CountryDelegate countryDelegate;
	
	@Autowired
	@Qualifier("cityDelegate")
	private CityDelegate cityDelegate;
	
	@Autowired
	@Qualifier("genericMessageProducer")
	private GenericMessageProducer genericMessageProducer;
	
	@Autowired
	@Qualifier("systemValuesDelegate")
	private SystemValuesDelegate systemValuesDelegate;
	
	@Autowired
	@Qualifier("fileHandlerDelegate")
	private FileHandlerDelegate fileHandlerDelegate;
	
	@Autowired
	@Qualifier("employmentVisaDelegate")
	private EmploymentVisaDelegate employmentVisaDelegate;
	
	@Autowired
	@Qualifier("buisnessValidationManager")
	private BuisnessValidationManager buisnessValidationManager;
	
	@Autowired
	private AppMetaDataDAO appMetaDataDAO;
	
//	@Autowired
//	@Qualifier("generalAdminDelegate")
//	private GeneralAdminDelegate generalAdminDelegate;
	
	@Autowired
	@Qualifier("emirateDelegate")
	private EmirateDelegate emirateDelegate;
	
	@Autowired
	@Qualifier("emirateCityDelegate")
	private EmirateCityDelegate emirateCityDelegate;
	
	@Autowired
	@Qualifier("messageInboxDAO")
	private MessageInboxDAO messageInboxDAO;
	
	@Autowired
	@Qualifier("ftlProcessorManager")
	private FtlProcessorManager ftlProcessorManager;

/*	
	@Autowired
	@Qualifier("smanSubDao")	
	private SManSubDao smanSubDao;
	
	@Autowired
	@Qualifier("smanBaseDao")	
	private SManBaseDao smanBaseDao;
*/	

//	@Autowired
//	@Qualifier("userfacadeapi")
//	private UserDelegate userDelegate;
	
//	@Autowired(required=false)
//	@Qualifier("UserEJB")
//	private UserEJBLocal userEJBLocal;
	
	@RequestMapping(value="/addmess", method= RequestMethod.GET)
	@Transactional
	public void addMes(HttpServletRequest request, HttpServletResponse response){
		MessageInbox messageInboxTask = new MessageInbox();
		messageInboxTask.setMiMsgType(MessageInbox.MESSAGE_TYPE_TASK);
		messageInboxTask.setMiSentOn(new Date());
		messageInboxTask.setMiActionFlag(MessageInbox.MESSAGE_ACTION_FLAG_NOT_DONE);
		messageInboxTask.setMiDtls("PLEASE RESUBMIT INFO !!");//:TODO notmal details
		messageInboxTask.setMiSubject("PLEASE RESUBMIT INFO !!");//:TODO normal subject
		messageInboxTask.setTackNameCode(TaskMaster.__ALL_RESUBMIT);
		messageInboxTask.setAppId(1220l);
		
		messageInboxDAO.add(messageInboxTask);
		
		MessageInbox messageInboxTask1 = new MessageInbox();
		messageInboxTask1.setMiMsgType(MessageInbox.MESSAGE_TYPE_TASK);
		messageInboxTask1.setMiSentOn(new Date());
		messageInboxTask1.setMiActionFlag(MessageInbox.MESSAGE_ACTION_FLAG_NOT_DONE);
		messageInboxTask1.setMiDtls("PLEASE RESUBMIT INFO !!");//:TODO notmal details
		messageInboxTask1.setMiSubject("PLEASE RESUBMIT INFO !!");//:TODO normal subject
		messageInboxTask1.setTackNameCode(TaskMaster.__ALL_RESUBMIT);
		messageInboxTask1.setAppId(11220l);
		
		messageInboxDAO.add(messageInboxTask1);
		
		System.out.println("atata");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public void home(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.getWriter().println("isAuthenticated: "+securityService.isAuthenticated());
			response.getWriter().println("isEmploye: "+securityService.isCompanyEmployee());
			response.getWriter().println("isCompanyAdmin: "+securityService.isCompanyAdmin());
			response.getWriter().println("isGeneralAdmin: "+securityService.isGeneralAdmin());
			response.getWriter().println("isITAdmin: "+securityService.isGeneralAdmin());
			response.getWriter().println("isDEFAULTUSER: "+securityService.isDefaultUser());
			response.getWriter().println("UserVO: "+getUserVO());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//	@RequestMapping(value="/valBuis", method = RequestMethod.GET)
//	@Transactional
//	public @ResponseBody String validateBuisness() throws Throwable {
//		ae.pcfc.etks.online.common.vo.UserVO userVO = userDelegate.findUserByUserName("tucadmin");
//		
//		return userVO.toString();
//	}
	
	@RequestMapping(value="/countries", method= RequestMethod.GET)
	public void process(HttpServletRequest request, HttpServletResponse response){
		try {
			response.getWriter().print(requestVariablesBean.getRequestedHost()+requestVariablesBean.getContextPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private int counter = 0;
	
	@RequestMapping(value="/testJMS", method= RequestMethod.GET)
	public void emirates(HttpServletRequest request, HttpServletResponse response){
		counter++;
		List<FileVO> fileVOs = new ArrayList<FileVO>();
		for(int i=0; i<10; i++){
			FileVO fileVO = new FileVO();
			fileVO.setFileName("blabla"+i+"counter"+counter);
			fileVOs.add(fileVO);
		}
		genericMessageProducer.sendFilesToGS(fileVOs);
	}
	
	@RequestMapping(value="/testFtl", method= RequestMethod.GET)
	public void testFtl(HttpServletRequest request, HttpServletResponse response) throws TemplateException{
		try {
			Map<Object, Object> params = new HashMap<Object, Object>();
			params.put("name", "Asna");
			response.getWriter().println(ftlProcessorManager.processFtlTemplate("test", params));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String returnHi(){
		return "hi";
	}
	
	@RequestMapping(value="/showEmirateCities/{emirateCode}", method= RequestMethod.GET)
	public void showEmirateCities(@PathVariable String emirateCode, HttpServletRequest request, HttpServletResponse response){
		PrintWriter writer = null;
		try {
			 writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println(emirateCityDelegate.getEmirateCitiesByEmirateCode(emirateCode));
	}
	
	@RequestMapping(value="/getForm")
	public ModelAndView getFileForm(){
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("maxSize", 12412);
		return new ModelAndView("error.fileupload", model);
	}
	
	
	@RequestMapping(value="/multipartTest", method= RequestMethod.POST)
	public void multipartTest(@ModelAttribute TestMultipartBean testMultipartBean,
			HttpServletRequest request, HttpServletResponse response){
		MultipartFile file = testMultipartBean.getFile();
		
		FileVO fileVO = new FileVO();
//		try {
//			fileVO.setFile(file.getBytes());
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		String originalFileName = file.getOriginalFilename();
		fileVO.setFileName(originalFileName);
		fileVO.setFileExt(originalFileName.substring(originalFileName.lastIndexOf('.'),originalFileName.length()));
		
		//fileHandlerDelegate.storeFile(fileVO);
		
//		System.out.println("********filename"+file.getName());
//		System.out.println("********fileSize"+file.getSize());
//		File dest = new File("D:\\test.test");
//		try {
//			dest.createNewFile();
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		try {
//			file.transferTo(dest);
//		} catch (IllegalStateException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		try {
//			response.getWriter().println("atatat");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	

	@RequestMapping(value="/showCities/{countryCode}", method= RequestMethod.GET)
	public void showAllSystemValues(@PathVariable String countryCode, HttpServletRequest request, HttpServletResponse response){
		PrintWriter writer = null;
		try {
			 writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println(cityDelegate.getCitiesByCountryCode(countryCode));
		writer.println(systemValuesDelegate.getAbscondStatus());
		writer.println(systemValuesDelegate.getAccomodationStatus());
		writer.println(systemValuesDelegate.getBanPriod());
		writer.println(systemValuesDelegate.getEmployeeSource());
		writer.println(systemValuesDelegate.getQualification());
		writer.println("*MEDICAL TYPE*");
		writer.println(systemValuesDelegate.getMedicalType());
		writer.println("*EMPLOYE TYPE TYPE*");
		writer.println(systemValuesDelegate.getEmployeeType());
		writer.println("*OPTION*");
		writer.println(systemValuesDelegate.getOption());
		writer.println("*PRIORITY*");
		writer.println(systemValuesDelegate.getPriority());
		
	}
	
	@RequestMapping(value="/checkFileTransmited/{fileId}", method= RequestMethod.GET)
	public void showAllSystemValues(@PathVariable Long fileId, HttpServletRequest request, HttpServletResponse response){
		
		FileVO fileVO = new FileVO();
		fileVO.setId(fileId);
		
		fileHandlerDelegate.updateTransferFlag(fileVO);
	}
	
	@RequestMapping(value="/deleteChecked", method= RequestMethod.GET)
	public void showAllSystemValues(HttpServletRequest request, HttpServletResponse response){
		
		fileHandlerDelegate.deleteTransferedFiles();
	}
	
	@RequestMapping(value="/hiberTest", method= RequestMethod.GET)
	@Transactional	
	public void showHiberTest(HttpServletRequest request, HttpServletResponse response){
/*		
		SManBase newSManBase = new SManBase();
		
		newSManBase.setBasedId(8L);
		newSManBase.setBaseChar("DATA_8");
		newSManBase.setBaseInt(888);
		
		if(smanBaseDao != null) {
			
			try {
				smanBaseDao.add(newSManBase);		
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			
			try {
				SManBase smanBase = smanBaseDao.findById(1L);
				
				System.out.println("-------------------------------");

				System.out.println("smanBase.getBasedId()	= " + smanBase.getBasedId());
				System.out.println("smanBase.getBaseInt() 	= " + smanBase.getBaseInt());
				System.out.println("smanBase.getBaseChar() 	= " + smanBase.getBaseChar());
				
				System.out.println("-------------------------------");
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			
		}
*/		
/*
		if(smanSubDao != null) {
			
			try {
				SManSub smanSub = smanSubDao.findById(1L);
						
				System.out.println("-------------------------------");

				System.out.println("smanSub.getSubId() 		= " + smanSub.getSubId());
				System.out.println("smanSub.getSubChar() 	= " + smanSub.getSubChar());
				System.out.println("smanSub.getSubInt() 	= " + smanSub.getSubInt());

				System.out.println("smanSub.getSmanBase().getBasedId() 	= " + smanSub.getSmanBase().getBasedId());
				System.out.println("-------------------------------");
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			
		} else {
			System.out.println("smanSubDao == null");
		}
		
		if(smanBaseDao != null) {
			
		} else {
			System.out.println("smanBaseDao == null");
		}
		
*/		
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/mapingTest", method= RequestMethod.GET)
	public void mapingTest(HttpServletRequest request, HttpServletResponse response){
		
		EmploymentVisaLicenseInfo employmentVisaLicenseInfo = new EmploymentVisaLicenseInfo();
		
		employmentVisaLicenseInfo.setAirFare(1002l);
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 1990);
		calendar.set(Calendar.MONTH, Calendar.JULY);
		calendar.set(Calendar.DAY_OF_MONTH, 22);
		employmentVisaLicenseInfo.setDateOfBirth(calendar.getTime());
		employmentVisaLicenseInfo.setEmployeeSource(123);
		employmentVisaLicenseInfo.setEmployeeType("321");
		employmentVisaLicenseInfo.setExpiryDate(new Date());
		employmentVisaLicenseInfo.setIssueDate(new Date());
		employmentVisaLicenseInfo.setJobCode("987");
		employmentVisaLicenseInfo.setQualification("12345678l");
		employmentVisaLicenseInfo.setRpPeriod(456);
		employmentVisaLicenseInfo.setSalary(2500l);
		employmentVisaLicenseInfo.setSpokenLanguage1("1");
		employmentVisaLicenseInfo.setSpokenLanguage2("2");
		employmentVisaLicenseInfo.setSpokenLanguage3("3");
		employmentVisaLicenseInfo.setStrAccommodationAllowance("A");
		employmentVisaLicenseInfo.setStrAccommodationStatus("B");
		employmentVisaLicenseInfo.setStrAddressAbroad("D");
		employmentVisaLicenseInfo.setStrBankGuranteeFlag("C");
		employmentVisaLicenseInfo.setStrBirthPlace("BirthPlace");
		employmentVisaLicenseInfo.setStrBuilding("Building");
		employmentVisaLicenseInfo.setStrCity("City");
		employmentVisaLicenseInfo.setStrCityOfIssue("CityOfIssue");
		employmentVisaLicenseInfo.setStrCurentlyInUAE("Y");
		employmentVisaLicenseInfo.setStrCurrentVisaType("CurrentVisaType");
		employmentVisaLicenseInfo.setStrEmirate("Emirate");
		employmentVisaLicenseInfo.setStrEmployeeStatus("D");
		employmentVisaLicenseInfo.setStrEntryPermitCollectionMethod("Entry");
		employmentVisaLicenseInfo.setStrFamilyName("FamilyName");
		employmentVisaLicenseInfo.setStrFatherName("FatherName");
		employmentVisaLicenseInfo.setStrFlatNO("123");
		employmentVisaLicenseInfo.setStrFoodAllowance("Y");
		employmentVisaLicenseInfo.setStrGender("M");
		employmentVisaLicenseInfo.setStrIDCardFlag("Y");
		employmentVisaLicenseInfo.setStrMaritalStatus("Y");
		employmentVisaLicenseInfo.setStrMedicalType("Y");
		employmentVisaLicenseInfo.setStrMotherName("MotherName");
		employmentVisaLicenseInfo.setStrNameInPassport("name in passport");
		employmentVisaLicenseInfo.setStrNationality("Ukraine");
		employmentVisaLicenseInfo.setStrOriginCity("Origin City");
		employmentVisaLicenseInfo.setStrOtherAllowance("Y");
		employmentVisaLicenseInfo.setStrPassportNo("PassportNumber");
		employmentVisaLicenseInfo.setStrPassportStatus("Y");
		employmentVisaLicenseInfo.setStrPOBox("POBOX");
		employmentVisaLicenseInfo.setStrPostNo("1234");
		employmentVisaLicenseInfo.setStrPreviousNationality("PrevNationality");
		employmentVisaLicenseInfo.setStrPriority("Priority");
		employmentVisaLicenseInfo.setStrReligion("Religion");
		employmentVisaLicenseInfo.setStrStatus("A");
		employmentVisaLicenseInfo.setStrStreet("Street");
		employmentVisaLicenseInfo.setStrTelephoneOffice("235235235");
		employmentVisaLicenseInfo.setStrTelephoneOfficeExtension("23523523523");
		employmentVisaLicenseInfo.setStrTelephoneRisidence("3");
		employmentVisaLicenseInfo.setStrTransportation("Y");
		employmentVisaLicenseInfo.setStrVisaType("Visa Type");
		employmentVisaLicenseInfo.setStrZone("ZONE");
		employmentVisaLicenseInfo.setStrCountryOfIssue("Countryofissue");
		
		EmployeeDetailsVO employeeDetailsVO = new EmployeeDetailsVO();
		mapper.map(employmentVisaLicenseInfo, employeeDetailsVO);
		PassportDetailsVO passportDetailsVO = new PassportDetailsVO();
		mapper.map(employmentVisaLicenseInfo, passportDetailsVO);
		PersonalDetailsVO personalDetailsVO = new PersonalDetailsVO();
		mapper.map(employmentVisaLicenseInfo, personalDetailsVO);
		AddressDetailsVO addressDetailsVO = new AddressDetailsVO();
		mapper.map(employmentVisaLicenseInfo, addressDetailsVO);
		
		EmployeVisaVO employeVisaVO = new EmployeVisaVO();
		employeVisaVO.setAddressDetailsVO(addressDetailsVO);
		//employeVisaVO.setCommentsVO(commentsVO)
		employeVisaVO.setEmployeeDetailsVO(employeeDetailsVO);
		employeVisaVO.setPassportDetailsVO(passportDetailsVO);
		employeVisaVO.setPersonalDetailsVO(personalDetailsVO);
		
		CommentsVO commentsVO = new CommentsVO();
		commentsVO.setComments("comments!!!");
		commentsVO.setStatus("STATUS");
		employeVisaVO.setCommentsVO(commentsVO);
		
		UserVO userVO = new UserVO();
		userVO.setUsername("tucadmin");
		
		employeVisaVO.setUserVO(userVO);
		
		employeVisaVO.setFileVOList(Collections.EMPTY_LIST);
		
		//String referenceId = employmentVisaDelegate.submit(employeVisaVO);
		try {
			response.getWriter().println(employeVisaVO);
			//response.getWriter().println("Reference ID = "+referenceId);
		} catch (IOException e) { 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	@Autowired
	@Qualifier("sequencesDOM")
	private SequencesDOM sequencesDOM;
	
	@RequestMapping(value="/seq", method= RequestMethod.GET)
	public @ResponseBody String sequenceTest(){
		return sequencesDOM.getNextFNPTransactionId().toString();
	}
	
	@RequestMapping(value="/testgrid", method= RequestMethod.GET)
	public ModelAndView testgrid(){
		return new ModelAndView("empgridtestpage");
	}
}
